const models = require("./models");
const token = require("./token");
// 引入bcrypt验证用户密码
const bcrypt = require("bcryptjs");

module.exports = {
  loginApi: async (req, res) => {
    let e = await models.User.findAll({
      where: {
        account: req.body.account,
      },
    });
    // 将Sequelize实例对象转换为普通的JavaScript对象 Sequelize查询返回的实例对象，无法直接添加新的属性
    const userData = e.map((item) => item.get({ plain: true }))[0];

    if (e.length == 0) {
      res.json({ status: 201, msg: "账号不存在", data: null });
    } else if (!bcrypt.compareSync(req.body.password, userData.password)) {
      res.json({ status: 201, msg: "密码错误", data: null });
    } else {
      // 为用户此次登录添加token
      const userToken = token.createToken(req.body);
      userData.token = userToken;
      res.json({
        status: 200,
        msg: "登录成功",
        data: userData,
      });
    }
  },
  registerApi: async (req, res) => {
    try {
      let e = await models.User.findAll({
        where: {
          account: req.body.account,
        },
      });
      if (e.length != 0) {
        res.json({ status: 201, msg: "账号已注册", data: e });
      } else {
        // 对密码进行加密
        req.body.password = bcrypt.hashSync(req.body.password, 10);
        const user = await models.User.create(req.body);
        res.json({ status: 200, msg: "成功", data: user });
      }
    } catch (error) {
      console.error("注册接口错误", error);
      res.json({ error: "Internal Server Error" });
    }
  },
  getArticleListApi: async (req, res) => {
    const articles = await models.Article.findAll({
      where: {
        className: req.query.className,
      },
    });
    res.json({ status: 200, msg: "成功", data: articles });
  },
  writeArticleListApi: async (req, res) => {
    let obj = {
      title: req.body.title,
      content: req.body.content,
      LikeCount: 0,
      pageView: 0,
      className: req.body.className,
      author: req.body.author,
      createdAt: new Date().getTime(),
      updatedAt: new Date().getTime(),
    };

    const article = await models.Article.create(obj);

    res.json({ status: 200, msg: "成功", data: article });
  },
};
